package elitech.vietnam.myfashion.dialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import elitech.vietnam.myfashion.MainActivity;
import elitech.vietnam.myfashion.R;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.City;
import elitech.vietnam.myfashion.entites.District;
import elitech.vietnam.myfashion.entites.Order;
import elitech.vietnam.myfashion.entites.OrderDetail;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.extend.HasHeaderSpinnerStringAdapter;
import elitech.vietnam.myfashion.utilities.Utilities;

public class ShippingDialog extends Dialog implements android.view.View.OnClickListener {

	private MainActivity		mContext;
	private Dialog				mDialog;

	private Button				mBtnContinue, mBtnCancel;
	private EditText			mTxtAddress, mTxtPhone, mTxtMemo;
	private TextView			mTxtWarn, mTxtShipping;
	private Spinner				mSpinCity, mSpinDistrict, mSpinPayment;
	private ArrayList<String>	mCityListString		= new ArrayList<String>();
	private ArrayList<String>	mDistrictListString	= new ArrayList<String>();
	private ArrayList<String>	mPaymentList		= new ArrayList<String>();
	private ArrayList<District>	mDistrictListTemp	= new ArrayList<District>();
	private ArrayAdapter<String>	mCityAdapter, mDistrictAdapter, mPaymentAdapter;
	private int						mCityLastPost, mDistrictLastPost;
	private boolean					isBuyNow	= false;
	private boolean					freeShip	= false;

	public ShippingDialog(MainActivity context, boolean isBuyNow) {
		super(context, R.style.Dialog);
		this.mDialog = this;
		this.isBuyNow = isBuyNow;
		this.mContext = context;
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		setContentView(R.layout.shipping);
		mTxtAddress = (EditText) findViewById(R.id.ship_txtAddress);
		mSpinCity = (Spinner) findViewById(R.id.ship_spinnerCity);
		mSpinDistrict = (Spinner) findViewById(R.id.ship_spinnerDistrict);
		mTxtPhone = (EditText) findViewById(R.id.ship_txtPhone);
		mTxtWarn = (TextView) findViewById(R.id.ship_txtWarn);
		mTxtShipping = (TextView) findViewById(R.id.ship_txtShippingFee);
		mTxtMemo = (EditText) findViewById(R.id.ship_txtMemo);
		mSpinPayment = (Spinner) findViewById(R.id.ship_spinnerPayment);

		mBtnContinue = (Button) findViewById(R.id.ship_btnContinue);
		mBtnCancel = (Button) findViewById(R.id.ship_btnCancel);

		freeShip = isFreeShip();
		mTxtShipping.setText(R.string.free);
		mCityAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mCityListString);
		mCityAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSpinCity.setAdapter(mCityAdapter);

		mDistrictAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, mDistrictListString);
		mDistrictAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSpinDistrict.setAdapter(mDistrictAdapter);

		mPaymentList.addAll(Arrays.asList(mContext.getResources().getStringArray(R.array.payment)));
		mPaymentAdapter = new HasHeaderSpinnerStringAdapter(mContext, android.R.layout.simple_spinner_item, mPaymentList);
		mPaymentAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
		mSpinPayment.setAdapter(mPaymentAdapter);
		mSpinPayment.setSelection(mPaymentList.size() - 1);

		mTxtAddress.setText(mContext.mUser.Address);
		mTxtPhone.setText(mContext.mUser.Phone);
		mCityLastPost = mContext.mUser.City;
		mDistrictLastPost = mContext.mUser.District;

		if (mContext.mListDistrict.size() == 0) {
			GetListDistrict();
		}

		if (mContext.mListCity.size() == 0) {
			GetListCity();
		} else {
			ListCityToListString();
		}

		mBtnContinue.setOnClickListener(this);
		mBtnCancel.setOnClickListener(this);

		mSpinCity.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
				ListDistrictToListString(mContext.mListCity.get(pos).Id);
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {}
		});

		if (!freeShip)
			mSpinDistrict.setOnItemSelectedListener(new OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) {
					mTxtShipping.setText(Utilities.numberFormat(mDistrictListTemp.get(mSpinDistrict.getSelectedItemPosition()).Ship) + " VNĐ");
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0) {}
			});
	}

	private void ListCityToListString() {
		for (City city : mContext.mListCity) {
			mCityListString.add(city.Name);
		}
		mCityAdapter.notifyDataSetChanged();
		if (mCityLastPost < mCityListString.size())
			mSpinCity.setSelection(mCityLastPost);
	}

	private void ListDistrictToListString(int IdCity) {
		mDistrictListString.clear();
		mDistrictListTemp.clear();
		for (District district : mContext.mListDistrict) {
			if (district.Publish == IdCity) {
				mDistrictListString.add(district.Name);
				mDistrictListTemp.add(district);
			}
		}
		mDistrictAdapter.notifyDataSetChanged();
		if (IdCity == mContext.mListCity.get(mCityLastPost).Id && mDistrictLastPost < mCityListString.size())
			mSpinDistrict.setSelection(mDistrictLastPost);
		else
			mSpinDistrict.setSelection(0);
		if (!freeShip)
			mTxtShipping.setText(Utilities.numberFormat(mDistrictListTemp.get(mSpinDistrict.getSelectedItemPosition()).Ship) + " VNĐ");
	}

	public void GetListCity() {
		new CallServiceTask() {
			protected void onPreExecute() {
				mContext.mLoadingDialog.show();
			};

			private ArrayList<City>	rs	= new ArrayList<City>();

			public void work() {
				try {
					rs = service.getListCity();
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mContext.mListCity.addAll(rs);
				ListCityToListString();
				mContext.mLoadingDialog.dismiss();
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);;
	}

	public void GetListDistrict() {
		new CallServiceTask() {
			private ArrayList<District>	rs	= new ArrayList<District>();

			public void work() {
				try {
					rs = service.getListDistrict();
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mContext.mListDistrict.addAll(rs);
			};
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public void Purchase() {
		if (mTxtAddress.getText().toString().trim().length() != 0 && mTxtPhone.getText().toString().trim().length() != 0
				&& mDistrictListTemp.size() != 0 && mSpinPayment.getSelectedItemId() < mPaymentAdapter.getCount()) {
			if (mContext.mOrder == null) {
				mContext.mOrder = new Order();
			}

			if (mContext.mBuyNowOrder == null) {
				mContext.mBuyNowOrder = new Order();
			}

			final Order newOrder = (isBuyNow) ? mContext.mBuyNowOrder : mContext.mOrder;

			newOrder.Address = mTxtAddress.getText().toString();
			newOrder.City = mCityListString.get(mSpinCity.getSelectedItemPosition());
			newOrder.State = mDistrictListString.get(mSpinDistrict.getSelectedItemPosition());
			newOrder.Phone = mTxtPhone.getText().toString();
			newOrder.Memo = mTxtMemo.getText().toString();
			newOrder.Email = mContext.mUser.Email;
			newOrder.Name = mContext.mUser.Name;

			newOrder.ShippingFee = (freeShip) ? 0 : mDistrictListTemp.get(mSpinDistrict.getSelectedItemPosition()).Ship;
			newOrder.Payment = mSpinPayment.getSelectedItemPosition();

//			mContext.mUser.Address = mTxtAddress.getText().toString();
//			mContext.mUser.City = mSpinCity.getSelectedItemPosition();
//			mContext.mUser.District = mSpinDistrict.getSelectedItemPosition();
//			mContext.mUser.Phone = mTxtPhone.getText().toString();
			
			new OkCancelWarnningDialog(mContext, getContext().getString(R.string.areyousure)) {
				public void onOk() {
					new CallServiceTask() {
						private int				rs	= 0;
						private ProgressDialog	mLoading;

						protected void onPreExecute() {
							mLoading = new ProgressDialog(mContext);
							mLoading.setCancelable(false);
							mLoading.setMessage(getContext().getString(R.string.loading));
							mLoading.show();
						};

						public void work() {
							try {
								rs = service.newOrder(mContext.mUser.Id, newOrder.Email, newOrder.Name, newOrder.Address, newOrder.City, newOrder.State, newOrder.Phone,
										newOrder.Payment, 0, newOrder.ShippingFee, newOrder.Memo, mContext.ConvertToJson(newOrder.ListDetail));
							} catch(Exception e) {
								e.printStackTrace();
							}
						};

						protected void onPostExecute(Void result) {
							mLoading.dismiss();
							if (rs < 1) {
								if (!mContext.isConnectionErrorShow) {
									mContext.isConnectionErrorShow = true;
									new ConnectionErrorDialog(mContext) {
										public void TryAgain() {
											Purchase();
										};
									}.show();
								}
								return;
							} else {
								Toast.makeText(mContext, mContext.getString(R.string.ordersuccessful), Toast.LENGTH_SHORT).show();
								if (isBuyNow)
									mContext.mBuyNowOrder = new Order();
								else
									mContext.mOrder = new Order();
								mDialog.dismiss();
							}
						};
					}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);;
				};
			}.show();
		} else {
			mTxtWarn.setText(mContext.getString(R.string.shippingwarn));
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ship_btnContinue:
			Purchase();
			break;
		case R.id.ship_btnCancel:
			this.dismiss();
			break;
		}
	}

	private boolean isFreeShip() {
		try {
			Order order = (isBuyNow) ? mContext.mBuyNowOrder : mContext.mOrder;
			long mTotal = 0;
			for (OrderDetail detail : order.ListDetail) {
				mTotal += detail.PriceVN * detail.Quantity;
				if (mTotal > 1000000)
					return true;
			}
		} catch (Exception e) {}
		return false;
	}
}
